<template>
  <UniDataCheckbox
    :multiple="multiple"
    v-bind="getProps"
    :localdata="getLocalData"
    v-model="data"
    @change="onChange"
  />
</template>

<script setup lang="ts">
  import UniDataCheckbox from '../uni_modules/uni-data-checkbox/uni-data-checkbox.vue';
  import { isString } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';
  import { computed, type PropType, ref, watch } from 'vue';
  import { useFormItem } from '../hooks/useContext';
  import { type Localdata } from '../types';
  import { isArray } from 'lodash-es';

  const props = defineProps({
    modelValue: [String, Number, Array],
    localdata: Array as PropType<Localdata[]>,
    multiple: propTypes.bool.def(false),
  });

  const { getProps, setFormModel } = useFormItem(props);
  const data = ref<string | number | (string | number)[]>([]);

  const emit = defineEmits(['update:modelValue']);

  watch(
    [() => getProps.value.modelValue, () => props.modelValue],
    ([v1, v2]) => {
      let val = v1 || v2;
      if (props.multiple || getProps.value.multiple) {
        if (isString(val)) val = val.split(',');
        if (isArray(val)) {
          val = val?.map((v: number | string) => v.toString())
        };
      }
      data.value = val;
    },
    {
      immediate: true,
    },
  );

  const getLocalData = computed(() => {
    const localData = props.localdata || (getProps.value.localdata as Localdata[]);
    return localData.map((v) => ({
      value: v.value.toString(),
      text: v.text,
    }));
  });

  function onChange(e: { detail: { value: string | number | (string | number)[]; data: any } }) {
    const { value, data } = e.detail;
    setFormModel(value);
    emit('update:modelValue', value);
  }
</script>

<style scoped></style>
